import { onMounted, reactive, ref, watch, computed } from 'vue'
import { getAllArticle } from '@/api/article'
import { getCateList as getCateListApi } from '@/api/cate'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'

export const columns = [
  {
    name: '标题',
    dataIndex: 'title',
    key: 'title'
  },
  {
    title: '分类名字',
    dataIndex: 'cate_name',
    key: 'cate_name'
  },
  {
    title: '发布时间',
    dataIndex: 'time',
    key: 'time'
  },

  {
    title: '操作',
    key: 'action'
  }
]

export const articleList = ref([])

export let articleParams = reactive({
  skip: 0,
  limit: 10,
  cate_id: '',
  cateName: '全部',
  author: '',
  title: ''
})

export let pagination = reactive({
  current: 1,
  total: 0,
  defaultPageSize: 20,
  position: ['bottomCenter'],
  hideOnSinglePage: true
})

export function getArticleList() {
  message.loading({ content: '加载中!', duration: 2 })

  let _articleParams = { ...articleParams }

  Reflect.deleteProperty(_articleParams, 'cateName') //  删除   这是es6的反射的写法

  getAllArticle(_articleParams).then((res: any) => {
    console.log(res)
    if (res.code == 0) {
      pagination.total = res.total

      articleList.value = res.data.map((v: any) => {
        v.time = dayjs(v.time).format('YYYY MM-DD HH:mm') //  时间戳转时间
        return v
      })
    }
  })
}

//  获取分类数据

export let cateList = ref<any[]>([])

function getCateList() {
  getCateListApi().then((res: any) => {
    console.log(res)

    res.unshift({
      _id: '',
      name: '全部'
    })
    cateList.value = res

    console.log(cateList.value)
  })
}

//  tableChange
//  文档看仔细

export const tableChange = (current: any, pageSize: number) => {
  //   console.log(current)
  //   console.log(pageSize)
  articleParams.limit = pageSize
  articleParams.skip = (current - 1) * pageSize
  getArticleList()
}

export function cateChange(e: any, i: any) {
  articleParams.cate_id = e
  articleParams.cateName = getCateName(e)
}

function getCateName(id: string) {
  let item = (cateList as any).value.find((v: any) => {
    return v._id === id
  })
  return item.name
}

export function search() {
  console.log(articleParams)

  pagination.current = 1
  articleParams.skip = 0
  getArticleList()
}

export default function () {
  onMounted(() => {
    getArticleList()
    getCateList() //  获取分类
  })
}
